import {http} from '../http';
import {PagingModel} from '../models/BaseModel';
import {DeviceStatus} from '@/enums/devices';
export type DeviceType = 'inv' | 'bat' | 'meter';
type DeviceState = keyof typeof DeviceStatus;

export interface DeviceCategoryModel {
  id: string;
  name: string;
  code: string;
  mainImage: null | string;
  parentId: string;
  networkType: string;
  protocolType: null | string;
  mqttServer: null | string;
  mqttName: null | string;
  mqttPwd: null | string;
  deviceSource: null | string;
  level: number;
  sort: number;
  status: number;
  remark: string;
  children?: DeviceCategoryModel[] | null;
}

// 设备相关接口类型定义
export interface UserEquipmentDTO {
  id?: string;
  deviceName: string;
  deviceSn: string;
  image?: string;
  stationId?: number;
  userId?: number;
  email?: string;
  categoryId?: number;
  categoryName?: string;
  seriesId?: number;
  seriesName?: string;
  modelId?: number;
  modelName?: string;
  status?: number;
  alert: 0 | 1 | 2;
  deviceId?: string;
  deviceType: DeviceType;
}

export type EquipSetCommand = Record<
  keyof InverterStateDTO,
  string | number | null
>;

export type AppPvTimeIndicatorDTO = Record<string, PVTimeIndicatorDTO[]>;
export type InverterType = {
  stationId: number;
  sn: string;
  sign: number;
  dvcType: DeviceType;
  devStatus: DeviceState;
  singleStrength: number;
  runTime: number;
  deviceImage: string;
  runStatus: number;
  deviceName: string;
  lastUpdateTime: string;
  pvNum: number;
  dayOutPower: number;
  totalOutPower: number;
  pvTotalPower: string;
  alarmNum: number;
  pvList: {
    power: number;
    volt: number;
    curr: number;
  }[];
  deviceId: number;
  categoryName: string;
  moduleVersion: string;
  mac: string;
  outPower: number;
  outList: {
    powerTotal: number;
    voltage: number;
    current: number;
  }[];
  iccId?: string;
};
export interface PVTimeIndicatorDTO {
  time: string;
  powerGen?: number;
  pvVoltage?: number;
  pvCurrent?: number;
  pvPower?: number;
  outVoltage?: number;
  outCurrent?: number;
  outPower?: number;
}

export interface InverterStateDTO {
  deviceSn: string;
  shutdown?: number;
  ratePower?: number;
  ratePowerFactor?: number;
  ratePowerReal?: number;
}

export interface OutDTO {
  powerTotal: number;
  voltage: number;
  current: number;
}

export interface PowerGenDTO {
  genTotal: number;
  genDay: number;
}

export interface PvPowerDTO {
  powerTotal: number;
  powerPv1: number;
  powerPv2: number;
  powerPv3: number;
  powerPv4: number;
}

export interface EquipTimeIndicatorDTO {
  time: string;
  power: number;
  voltage: number;
  current: number;
}

export interface GenEleDTO {
  time: string;
  powerGen: number;
}

export interface GenEleQueryParams {
  stationId?: number;
  start?: string;
  end?: string;
  grain?: number; // 粒度：月-1，年-2，总-3
  deviceSns: string[];
  year?: string;
  month?: string;
  day?: string;
  deviceType: DeviceType;
}

export interface AppEquipmentDTO {
  pageNum: number;
  pageSize: number;
  id: number;
  stationId: number;
  deviceName: string;
  deviceSn: string;
  deviceType: DeviceType;
  coverImage: string;
  statusCode: string;
  deviceStatus: DeviceState;
  categoryId: number;
  userId: number;
  email: string;
  timeZone: string;
  defaultStation: number;
  networkType: string;
  phase: number;
  lastUpdateTime: string;
  singleStrength?: number;
  moduleType?: number;
  categoryName?: string;
}
export interface StationDTO {
  records: AppEquipmentDTO[];
}

export interface EquipTimeIndicatorQueryParams {
  start?: string;
  endT?: string;
  grain?: number; // 粒度：分钟-1，小时-2
}

export interface EquipmentAlarm {
  level: number;
  viewType?: number;
  code: string;
  message: string;
  ct: string;
}

export interface InstStatisticsData {
  total: number;
  online: number;
  offline: number;
  normal: number;
  alarm: number;
}

export interface InstGrainStatisticsItem {
  time: string;
  instNum: number;
}

export interface InstGrainStatisticsParams {
  grain?: 1 | 2 | 3; // 粒度：月-1，年-2，总-3
}

export interface InstListQueryParams {
  pageNum?: number;
  pageSize?: number;
  key?: string;
  online?: number;
  alarm?: number;
}

export interface InstListItem {
  sn: string;
  name: string;
  image: string;
  online: number;
  dvcType: DeviceType;
  deviceTypeString: string;
  alert: number;
}

export interface InstListResponse {
  records: InstListItem[];
  total: number;
  size: number;
  current: number;
  optimizeCountSql: string;
  searchCount: string;
}

export interface InstAlarmQueryParams {
  pageNum?: number; // 页号，默认值：1
  pageSize?: number; // 页码，默认值：10
  sn: string; // 设备SN
}

export interface InstAlarmItem {
  ct: string;
  level: number;
  code: string;
  message: string;
}

export interface InstAlarmResponse {
  records: InstAlarmItem[];
  total: number;
  size: number;
  current: number;
  optimizeCountSql: string;
  searchCount: string;
}

// API 接口定义
export const deviceApi = {
  /**
   * 创建用户设备
   * POST /v1/biz/equipments
   */
  createUserEquipment: (data: UserEquipmentDTO) => {
    return http.post<UserEquipmentDTO>('/biz/v1/biz/equipments', data);
  },

  /**
   * 获取用户设备详情
   * GET /v1/biz/equipments/{id}
   */
  getUserEquipment: (id: number) => {
    return http.get<UserEquipmentDTO>(`/biz/v1/biz/equipments/${id}`);
  },

  /**
   * 根据电站ID查询用户设备
   * GET /v1/biz/equipments/station/{stationId}
   */
  getUserEquipmentsByStation: (stationId: number) => {
    return http.get<UserEquipmentDTO[]>(
      `/biz/v1/biz/equipments/station/${stationId}`,
    );
  },

  setEquipmentParams: (data: EquipSetCommand) => {
    return http.post<boolean>(`/biz/v1/biz/device/inverter/set`, data, {
      timeout: 30 * 1000,
    });
  },

  /**
   * 查询逆变器设备的PV时间数据
   * GET /v1/biz/equipments/pv/time/{id}
   */
  getPvTimeIndicator: (params: GenEleQueryParams) => {
    return http.get<AppPvTimeIndicatorDTO>(
      `/biz/v1/biz/device/inverter/pv/statics`,
      params,
    );
  },

  /**
   * 查询逆变器设备时间数据
   * GET /v1/biz/equipments/equip/time/{id}
   */
  getEquipTimeIndicator: (params?: GenEleQueryParams) => {
    return http.get<AppPvTimeIndicatorDTO>(
      `/biz/v1/biz/device/inverter/out/statics`,
      params,
    );
  },

  /**
   * 查询电站的发电量统计数据
   * GET /v1/biz/station/gen/{id}
   */
  queryGenEle: (signal: AbortSignal, params?: GenEleQueryParams) => {
    return http.get<{
      powerGen: GenEleDTO[];
    }>(`/biz/v1/biz/device/statistics`, params, {
      signal,
      skipErrorHandler: true,
    });
  },

  /**
   * 获取电站用户设备列表数据
   * GET /v1/biz/station/equip/{id}
   */
  getStationEquipment: (params: {
    pageNum?: number;
    pageSize?: number;
    deviceName?: string;
    deviceSn?: string;
  }) => {
    return http.get<PagingModel<AppEquipmentDTO>>(`/biz/v1/biz/device`, params);
  },
  checkSNCode: (params: {deviceSn: string}) => {
    return http.get<boolean>(`/biz/v1/biz/device/check`, params);
  },

  /**
   * 添加设备（使用创建用户设备接口）
   * POST /v1/biz/equipments
   */
  addDevice: (params: {
    deviceSn: string;
    deviceName: string;
    stationId?: number | string | undefined;
    coverImage: string;
    deviceType?: DeviceType;
    categoryId: number;
  }) => {
    return http.post<UserEquipmentDTO>('/biz/v1/biz/device/add', params);
  },
  unbindDevice: (id: number | string) => {
    return http.delete<boolean>(`/biz/v1/biz/device/${id}`);
  },

  /**
   * 查询设备告警信息
   * GET /v1/biz/equipments/alarm/{sn}
   */
  getEquipmentAlarms: (sn: string) => {
    return http.get<EquipmentAlarm[]>(`/biz/v1/biz/equipments/alarm/${sn}`);
  },

  /**
   * 获取安装商统计数据
   * GET /v1/biz/inst/all/statics
   */
  getInstStatistics: () => {
    return http.get<InstStatisticsData>('/biz/v1/biz/inst/all/statics');
  },

  /**
   * 获取安装商列表
   * GET /v1/biz/inst/list
   */
  getInstList: (params?: InstListQueryParams) => {
    return http.get<InstListResponse>('/biz/v1/biz/inst/list', params);
  },
  /**
   * 获取安装商设备告警列表
   * GET /v1/biz/inst/alarm
   * @param params 查询参数
   * @param params.pageNum 页号，默认值：1
   * @param params.pageSize 页码，默认值：10
   * @param params.sn 设备SN（必填）
   */
  getInstAlarmList: (params: InstAlarmQueryParams) => {
    return http.get<InstAlarmResponse>('/biz/v1/biz/inst/alarm', params);
  },

  getDeviceCategories: () => {
    return http.get<DeviceCategoryModel[]>('/biz/v1/biz/device/category');
  },
  getInverterInfo: (params: {deviceSn: string; stationId: number}) => {
    return http.get<InverterType>('/biz/v1/biz/device/inverter/detail', params);
  },
  getBatteryInfo: (params: {deviceSn: string; stationId: number}) => {
    return http.get<InverterType>('/biz/v1/biz/device/inverter/detail', params);
  },
  getMeterInfo: (params: {deviceSn: string; stationId: number}) => {
    return http.get<InverterType>('/biz/v1/biz/device/meter/detail', params);
  },
  getAlarmList: (params: {
    deviceSn: string;
    deviceType: DeviceType;
    pageSize?: number;
    pageNum?: number;
  }) => {
    return http.get<PagingModel<InstAlarmItem>>(
      '/biz/v1/biz/device/alarm/list',
      params,
    );
  },
  getInverterState: (params: {deviceSn: string}) => {
    return http.get<InverterStateDTO>(
      '/biz/v1/biz/device/inverter/read',
      params,
    );
  },
  getStationStatistics: (signal: AbortSignal, params: GenEleQueryParams) => {
    return http.get<
      {
        viewData: Partial<{
          pvPowerGen: number;
          loadUserGen: number;
          energyChargeGen: number;
          energyDischargeGen: number;
          gridConneGen: number;
          gridBuyGen: number;
        }>;
      } & Record<
        string,
        {
          time: string;
          value: string;
        }[]
      >
    >(`/biz/v1/biz/station/statistics`, params, {
      signal,
      skipErrorHandler: true,
    });
  },
};
